<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ queTitle }}</span>
      </div>
      <el-form
        ref="form"
        :model="directorysForm"
        :rules="qsRules"
        label-width="120px"
      >
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            @change="changeSubject"
            v-model="directorysForm.subjectID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in catalogueList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select
            v-model="directorysForm.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in subjectList"
              :key="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select
            v-model="directorysForm.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              :label="item.company"
              :value="item.id"
              v-for="item in enterpriseList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" prop="city">
          <el-select
            v-model="directorysForm.province"
            placeholder="请选择"
            style="width: 198px; margin-right: 3px"
            @change="getArea"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="item in cityList"
              :key="item"
            ></el-option>
          </el-select>
          <!-- 区 -->
          <el-select
            v-model="directorysForm.city"
            placeholder="请选择"
            style="width: 198px"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="item in areaList"
              :key="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select
            v-model="directorysForm.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              :label="item"
              :value="item"
              v-for="item in direction"
              :key="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group
            v-model="directorysForm.questionType"
            @change="changeRadio({})"
          >
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!-- 难度： -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="directorysForm.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 富文本 题干： -->
        <el-form-item label="题干：" class="quill" prop="question">
          <quill-editor
            @blur="question"
            :options="editorOption"
            v-model="directorysForm.question"
          ></quill-editor>
        </el-form-item>
        <!-- 选项： -->
        <el-form-item
          label="选项："
          prop="options"
          v-if="directorysForm.questionType !== 3"
        >
          <div
            class="option_item"
            v-for="item in directorysForm.options"
            :key="item.code"
          >
            <el-radio
              v-if="directorysForm.questionType === 1"
              @change="changeRadio(item)"
              v-model="item.isRight"
              style="margin-right: 0"
              :label="true"
              >{{ item.code }}：</el-radio
            >
            <el-checkbox
              v-if="directorysForm.questionType === 2"
              v-model="item.isRight"
              style="margin-right: 0"
              :label="true"
              >{{ item.code }}：</el-checkbox
            >
            <el-input v-model="item.title" style="width: 240px"></el-input>

            <el-upload
              class="uploadBox"
              action="https://jsonplaceholder.typicode.com/posts/"
              list-type="picture-card"
              :show-file-list="false"
              :on-success="
                (res, file) => {
                  handleAvatarSuccess(item, res, file)
                }
              "
            >
              <img
                v-if="item.img"
                :src="item.img"
                style="width: 100%; height: 100%"
              />
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button
            type="danger"
            @click="addOptions"
            :disabled="directorysForm.questionType === 1"
            size="small"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 解析视频： -->
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input
            v-model="directorysForm.videoURL"
            style="width: 398px"
          ></el-input>
        </el-form-item>
        <!-- 富文本 答案解析： -->
        <el-form-item label="答案解析：" class="quill" prop="answer">
          <quill-editor
            @blur="answer"
            :options="editorOption"
            v-model="directorysForm.answer"
          ></quill-editor>
        </el-form-item>
        <!-- 文本域 题目备注： -->
        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            type="remarks"
            :rows="4"
            v-model="directorysForm.remarks"
            style="width: 400px"
          >
          </el-input>
        </el-form-item>
        <!-- 试题标签： -->
        <el-form-item label="试题标签：" prop="tags">
          <el-select
            v-model="directorysForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择试题标签"
            style="width: 400px"
          >
            <el-option
              v-for="item in tags"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" v-if="!$route.query.id" @click="addQuestion"
            >确认提交</el-button
          >
          <el-button type="success" v-else @click="editQuestion"
            >修改提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/directorys' // 目录
import { simple as simpleCatalogue } from '@/api/hmmm/subjects' // 学科
import { simple as tags } from '@/api/hmmm/tags' // 标签
import { list as enterpriseList } from '@/api/hmmm/companys' // 企业
import { provinces, citys } from '@/api/hmmm/citys' // 所有城市
import { direction, questionType, difficulty } from '@/api/hmmm/constants' // 一些常量
import { add, update, detail } from '@/api/hmmm/questions' // 题库

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  ['image', 'link']
]
export default {
  name: 'questionsNew',
  data () {
    return {
      queTitle: '试题目录',
      //  富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: '请输入正文'
      },
      subjectList: [], // 获取目录
      catalogueList: [], // 获取学科
      enterpriseList: [], // 企业
      cityList: provinces(), // 所有城市
      areaList: '', // 城市下地区
      direction, // 方向
      questionType, // 题型
      difficulty, // 难度
      tags: '', // 标签
      backupscatalogID: '', // 备份一份目录,
      options: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ], // 这个是选项
      // 数据form
      directorysForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 所有城市
        city: '', // 城市下地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度：
        question: '', // 富文本题干：question
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ], // 选项：
        videoURL: '', // 解析视频
        answer: '', // 答案解析：富文本
        remarks: '', // 文本域 题目备注：
        tags: '' // 试题标签：
      },
      // 规则
      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }], // 城市
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ], // 富文本题干：
        answer: [
          {
            required: true,
            message: '请输入答案解析',
            trigger: ['blur', 'change']
          }
        ], // 答案解析：富文本
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ]
      }
    }
  },

  created () {
    // 学科简单列表
    this.getCatalogueList()
    // 获取企业列表
    this.getEnterpriseList()
    if (this.$route.query.id) {
      this.modify()
      this.queTitle = '修改目录'
    }
  },

  methods: {
    async modify () {
      // 回显
      const { data } = await detail({ id: this.$route.query.id })
      data.difficulty = +data.difficulty
      data.questionType = +data.questionType
      data.tags = data.tags.split(',')

      data.options.forEach((item) => {
        if (item.isRight === 1) {
          item.isRight = true
        }
      })

      this.backupscatalogID = data.catalogID // 备份一份目录名 number类型
      data.catalogID = data.directoryName // 赋值用来回显
      this.directorysForm = data

      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    // 校验题干
    question () {
      this.$refs.form.validateField(['question'])
    },
    // 答案解析
    answer () {
      this.$refs.form.validateField(['answer'])
    },

    // 获取// 学科简单列表
    async getCatalogueList () {
      const { data } = await simpleCatalogue()
      this.catalogueList = data
    },

    // change点了学科后出现目录
    async changeSubject () {
      // 清空目录
      this.directorysForm.catalogID = ''
      //  清空标签
      this.directorysForm.tags = null
      // 获取// 目录简单列表
      const { data } = await simple({
        subjectID: this.directorysForm.subjectID
      })
      this.subjectList = data
      // 获取标签
      const res = await tags({ subjectID: this.directorysForm.subjectID })
      this.tags = res.data
    },

    // 获取企业列表
    async getEnterpriseList () {
      const {
        data: { items }
      } = await enterpriseList()
      this.enterpriseList = items
    },

    // change根据市获取区
    getArea () {
      this.directorysForm.city = null
      // 城市和区域
      this.areaList = citys(this.directorysForm.province) // 区 // 城市下地区
    },

    // 单选框的change
    changeRadio (item) {
      this.directorysForm.options.forEach((item) => {
        item.isRight = false
      })
      item.isRight = true
    },

    // 图片上传成功的狗子
    handleAvatarSuccess (item, res, file) {
      item.img = file.url
    },

    // 添加选项
    addOptions () {
      const code = String.fromCharCode(this.directorysForm.options.length + 65)
      this.directorysForm.options.push({ ...this.options[0], code })
    },

    // 提交按钮
    addQuestion () {
      this.$refs.form.validate(async (boo) => {
        if (!boo) return this.$message.error('请填入数据')
        const data = {
          ...this.directorysForm,
          tags: this.directorysForm.tags.toString()
        }
        console.log(data, '这个是data')

        data.catalogID = this.directorysForm.catalogID

        data.difficulty = data.difficulty.toString()
        data.questionType = data.questionType.toString()
        const res = await add(data)
        console.log(res)
        // 清空表单
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      })
    },
    // 修改按钮
    editQuestion () {
      this.$refs.form.validate(async (boo) => {
        if (!boo) return this.$message.error('请填入数据')
        const data = {
          ...this.directorysForm,
          tags: this.directorysForm.tags.toString()
        }
        data.difficulty = data.difficulty.toString()
        data.questionType = data.questionType.toString()
        data.catalogID = this.backupscatalogID // 修改的时候赋值回来
        const res = await update(data)
        console.log(res, '修改成功')
        // 清空表单
        this.$message.success('修改成功')
        this.$router.go(-1)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.quill {
  margin-bottom: 34px;
}
.option_item {
  padding-bottom: 20px;
  height: 80px;
}
::v-deep .el-form-item__content {
  .uploadBox {
    position: relative;
    display: inline-block;
    margin-left: 4px;
    .el-icon-circle-close {
      position: absolute;
      top: -18px;
      left: 85px;
      font-size: 20px;
    }
  }
  .el-upload--picture-card {
    line-height: 58px;
    width: 98px;
    margin-top: -10px;
    height: 58px;
  }
}
.container {
  padding: 20px;
  ::v-deep .ql-editor {
    height: 200px;
  }
}
</style>
